﻿using Microsoft.AspNetCore.Http;
using Models.Common;
using Newtonsoft.Json;
using System;
using UtilsCache;
using UtilsORM;
using UtilsORM.MySqlData;
////using System.Web.Script.Serialization;

namespace GatewayServerService.Data
{
    public class DBIotMqLog
    {


        static string mqttLogSave = UtilAppsettingCache.getSetting("base:logSave");
        /// <summary>
        /// 写入mq日志
        /// </summary>
        /// <param name="mQReqModel"></param>
        /// <param name="msg"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool writeMQLog(string json, string type, string result)
        {

            //是否开启mq日志记录，保护emmc寿命
            if (mqttLogSave == "false")
            {
                return false;
            }
            EFYihongIotContext efgw = new EFYihongIotContext();
            // EFYihongIotContext efdc = new EFYihongIotContext();
            try
            {
                MQReqModel<object> mQReqModel = JsonConvert.DeserializeObject<MQReqModel<object>>(json);//
                if (mQReqModel == null) return false;
                CommandLogModel commandLogModel = mQReqModel.toGatewayData;
                if (commandLogModel == null)
                {
                    commandLogModel = new CommandLogModel();
                }

                iot_mq_log mqlog = new iot_mq_log();
                mqlog.ml_guid = Guid.NewGuid().ToString();
                mqlog.ml_mqguid = mQReqModel.guid;
                mqlog.ml_mqevent = mQReqModel.respEvent;
                mqlog.ml_gw_code = mQReqModel.gatewayCode;
                mqlog.ml_gw_d_guid = mQReqModel.gatewayDeviceGuid;
                mqlog.ml_device_guid = commandLogModel.d_guid;
                mqlog.ml_content = json;
                mqlog.ml_type = type;
                mqlog.ml_add_time = DateTime.Now;
                mqlog.ml_result = result;
                efgw.iot_mq_log.AddAsync(mqlog);
                efgw.SaveChanges();



                //dc_iot_mq_log dclog = new UtilsClassClone().CloneByReflection<iot_mq_log, dc_iot_mq_log>(mqlog);
                //efdc.dc_iot_mq_log.AddAsync(dclog);
                //efdc.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
    }
}
